import { defineStore } from 'pinia'
import { computed, ref } from 'vue'

export const userStore = defineStore('user', () => {
    const user = ref({
        username: '',
        token: ''
    })
    const isLogin = computed(() => {
        if (!user.value.token) {
            return false;
        }
        try {
            const payload = JSON.parse(atob(user.value.token.split('.')[1]));
            return payload.exp * 1000 > Date.now();
        } catch (e) {
            console.log(e);
            return false;
        }
    })
    const getToken = () => {
        if (!user.value.token) {
            if (localStorage.getItem('token')) {
                user.value.token = localStorage.getItem('token');
                user.value.username = localStorage.getItem('username');
                return user.value.token;
            }
        }
        return user.value.token;
    }

    const getUsername = () => {
        if (!user.value.username) {
            if (localStorage.getItem('username')) {
                user.value.token = localStorage.getItem('token');
                user.value.username = localStorage.getItem('username');
                return user.value.username;
            }
        }
        return user.value.username;
    }
    const saveToLocalStorage = (username, token) => {
        console.log(user.value)
        localStorage.setItem('username', username);
        localStorage.setItem('token', token);
        user.value.username = username;
        user.value.token = token;
    }
    const clearLocalStorage = () => {
        localStorage.removeItem('username');
        localStorage.removeItem('token');
        user.value.username = '';
        user.value.token = '';
        location.reload();
    }

    return {
        user,
        isLogin,
        saveToLocalStorage,
        getToken,
        getUsername,
        clearLocalStorage
    }
})